package com.wanchuang.qhbb.module.policy;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.adapter.PolicyItemAdapter;
import com.wanchuang.qhbb.adapter.PolicyItemBean;
import com.wanchuang.qhbb.adapter.PolicySelectBean;
import com.wanchuang.qhbb.base.BaseActivity;
import com.wanchuang.qhbb.base.MainApplication;
import com.wanchuang.qhbb.dialog.EditRateDialog;
import com.wanchuang.qhbb.dialog.PolicyDialog;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.proto.AgentPolicy;
import com.wanchuang.qhbb.proto.Mystock;
import com.wanchuang.qhbb.utils.GsonUtils;
import com.google.gson.reflect.TypeToken;
import com.wanchuang.qhbb.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

public class PolicyShareActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.rv_policy)
    RecyclerView rvPolicy;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.btn_sure)
    Button btnSure;
    @BindView(R.id.tv_goods)
    TextView tv_goods;
    private List<PolicyItemBean> mData = new ArrayList<>();
    private PolicyItemAdapter mAdapter;
    private List<PolicySelectBean> selectData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_policy_share);
        StatusBarUtil.setWhiteStatusBar(this);
        ButterKnife.bind(this);
        tv_goods.setMovementMethod(new ScrollingMovementMethod());
        tvName.setText(getIntent().getStringExtra("name"));
        tvTime.setText("注册时间：" + getIntent().getStringExtra("time"));
        initListener();
        initRecyclerView();
        selectData = GsonUtils.deSerializedFromJson(getIntent().getAction(),
                new TypeToken<List<PolicySelectBean>>() {
                }.getType());
        Log.e("mango", selectData.toString());
        initData();
    }

    private void initData() {
        mData.clear();
        for (int i = 0; i < selectData.size(); i++) {
            if (selectData.get(i).isSelect()) {
                PolicyItemBean titleBean = new PolicyItemBean();
                titleBean.setItemType(PolicyItemBean.TITLE);
                titleBean.setPolicy_name(selectData.get(i).getItem().getGoodsTab() + " " + selectData.get(i).getItem().getGoodsName()
                        + " " + selectData.get(i).getItem().getGoodsSerial()
                );
                titleBean.setPolicy_key(selectData.get(i).getItem().getGoodsId());
                titleBean.setPolicy_value(selectData.get(i).getItem().getStatus());
                mData.add(titleBean);
                for (int j = 0; j < selectData.get(i).getItem().getRatePolicyOptionCount(); j++) {
                    PolicyItemBean contentBean = new PolicyItemBean();
                    contentBean.setPolicy_value(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getPolicyValue());
                    contentBean.setPolicy_key(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getPolicyKey());
                    contentBean.setPolicy_name(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getPolicyName());
                    contentBean.setType(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getType());
                    contentBean.setIs_show(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getIsShow());
                    contentBean.setPolicy_img(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getPolicyImg());
                    contentBean.setValueEnum(selectData.get(i).getItem().getRatePolicyOptionList().get(j).getListList());
                    if (contentBean.getIs_show().equals("0")) {
                        contentBean.setItemType(PolicyItemBean.CONTENT_FOUR);
                    } else {
                        switch (contentBean.getType()) {
                            case "1":
                            case "2":
                                contentBean.setItemType(PolicyItemBean.CONTENT_ONE);
                                break;
                            case "5":
                                contentBean.setItemType(PolicyItemBean.CONTENT_TWO);
                                break;
                            case "10":
                                contentBean.setItemType(PolicyItemBean.CONTENT_THREE);
                                break;
                            default:
                                contentBean.setItemType(PolicyItemBean.CONTENT_ONE);
                                break;

                        }
                    }
                    mData.add(contentBean);
                }
                for (int j = 0; j < selectData.get(i).getItem().getEntryPolicyOptionCount(); j++) {
                    PolicyItemBean contentBean = new PolicyItemBean();
                    contentBean.setPolicy_value(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getPolicyValue());
                    contentBean.setPolicy_key(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getPolicyKey());
                    contentBean.setPolicy_name(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getPolicyName());
                    contentBean.setType(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getType());
                    contentBean.setIs_show(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getIsShow());
                    contentBean.setPolicy_img(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getPolicyImg());
                    contentBean.setValueEnum(selectData.get(i).getItem().getEntryPolicyOptionList().get(j).getListList());
                    if (contentBean.getIs_show().equals("0")) {
                        contentBean.setItemType(PolicyItemBean.CONTENT_FOUR);
                    } else {
                        switch (contentBean.getType()) {
                            case "1":
                            case "2":
                                contentBean.setItemType(PolicyItemBean.CONTENT_ONE);
                                break;
                            case "5":
                                contentBean.setItemType(PolicyItemBean.CONTENT_TWO);
                                break;
                            case "10":
                                contentBean.setItemType(PolicyItemBean.CONTENT_THREE);
                                break;
                            default:
                                contentBean.setItemType(PolicyItemBean.CONTENT_ONE);
                                break;
                        }
                    }
                    mData.add(contentBean);
                }
            }
        }
        Mystock.title_list.Builder builder = Mystock.title_list.newBuilder();
        builder.setType("4");
        Mystock.title_list data = builder.build();
        NetworkManager.INSTANCE.post(Apis.title_list, data.toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Mystock.title_list result = Mystock.title_list.parseFrom(bytes);
                List<Mystock.goods> list = result.getListDesList();
                StringBuilder des = new StringBuilder();
                for (int i = 0; i < list.size() - 1; i++) {
                    des.append(list.get(i).getGoodsSerial()).append("\n");
                }
                des.append(list.get(list.size() - 1).getGoodsSerial());
//                tv_goods.setText(des.toString());

            }

            @Override
            public void onError(int code, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void initListener() {
        backIv.setOnClickListener(v -> {
            finish();
        });
        tvTitle.setText("政策分配");
        btnSure.setOnClickListener(v -> {
            setPolicy();
        });

        tvEdit.setOnClickListener(v -> {
            PolicyDialog.Builder builder = new PolicyDialog.Builder(mContext);
            builder.setData(selectData);
            builder.setOnDialogClickListener((v1, positon) -> {
                initData();
                mAdapter.notifyDataSetChanged();
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());

        });


    }

    private void setPolicy() {
        AgentPolicy.set_policy.Builder builder = AgentPolicy.set_policy.newBuilder();
        builder.setOthersMemberId(getIntent().getType());
        for (int i = 0; i < mData.size(); i++) {
            if (mData.get(i).getItemType() == 0) {
                AgentPolicy.policy_goods_info.Builder builders = AgentPolicy.policy_goods_info.newBuilder();
                builders.setGoodsName(mData.get(i).getPolicy_name()).setGoodsId(mData.get(i).getPolicy_key())
                        .setStatus(mData.get(i).getPolicy_value());
                for (int j = i + 1; j < mData.size(); j++) {
                    if (mData.get(j).getItemType() == 0) break;
                    AgentPolicy.policy_option.Builder op_builder = AgentPolicy.policy_option.newBuilder();
                    op_builder.setPolicyName(mData.get(j).getPolicy_name())
                            .setPolicyKey(mData.get(j).getPolicy_key())
                            .setType(mData.get(j).getType())
                            .setPolicyImg(mData.get(j).getPolicy_img())
                            .setIsShow(mData.get(j).getIs_show())
                            .setPolicyValue(mData.get(j).getPolicy_value());
                    builders.addEntryPolicyOption(op_builder);
                }
                builder.addGoodsList(builders);
            }
        }


        Log.e("builder", "setPolicy: " + builder.build().toString());
        NetworkManager.INSTANCE.post(Apis.set_policy, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) {

            }

            @Override
            public void onError(int code, String errorMessage) {
                showToast(errorMessage);
                if (code == 200)
                    MainApplication.isRef = true;
                finish();
            }
        });

    }


    private void initRecyclerView() {
        rvPolicy.setLayoutManager(new LinearLayoutManager(mContext));
        rvPolicy.setAdapter(mAdapter = new PolicyItemAdapter(mData));
        // 每个item的点击事件
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            PolicyItemBean bean = mData.get(position);
            if (bean.getItemType() == 1) {
                EditRateDialog.Builder builder = new EditRateDialog.Builder(mContext);
                builder.setTitleText(bean.getPolicy_name());
                builder.setOnDialogClickListener((v, inputText) -> {
                    bean.setPolicy_value(inputText);
                    mAdapter.notifyItemChanged(position);
                });
                builder.setMessageText(bean.getType());
                EasyDialog build = builder.build();
                build.setCancelable(false);
                build.show(getSupportFragmentManager());
            } else if (bean.getItemType() == 3) {
                showSingleChoiceDialog(bean, position);
            }
        });
    }


    int yourChoice;

    private void showSingleChoiceDialog(PolicyItemBean bean, int position) {
        List<AgentPolicy.value_enum> valueEnumList = bean.getValueEnum();
        String[] valueItems = new String[valueEnumList.size()];
        String[] valueOther = new String[valueEnumList.size()];
        for (int i = 0; i < valueEnumList.size(); i++) {
            valueItems[i] = valueEnumList.get(i).getValue();
            valueOther[i] =  valueEnumList.get(i).getName();

        }
        yourChoice = 0;
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(PolicyShareActivity.this);
        singleChoiceDialog.setTitle("请选择模式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(valueOther, 0,
                (dialog, which) -> yourChoice = which);
        singleChoiceDialog.setPositiveButton("确定",
                (dialog, which) -> {
                        bean.setPolicy_value(valueItems[yourChoice]);
                        bean.setPolicy_other(valueOther[yourChoice]);
                        mAdapter.notifyItemChanged(position);
                });
        singleChoiceDialog.show();
    }


}
